<?php
namespace app\member\model;

use app\BaseModel;
use app\shop\model\IndexCouponRecord;
use think\facade\Db;

class StoredCoupon extends BaseModel
{
    //会员权益表
    protected $name = 'longbing_card_erp_stored_coupon';

    protected $append = [

        'stored_type'
    ];




    /**
     * @author chenniang
     * @DataTime: 2020-09-09 10:37
     * @功能说明:列表
     */
    public function storedList($dis,$page){

        $data = $this->where($dis)->order('top desc,id desc')->paginate($page)->toArray();

        return $data;

    }





    /**
     * @author chenniang
     * @DataTime: 2020-07-15 09:49
     * @功能说明:添加
     */
    public function storedAdd($data){

        $data['create_time'] = time();

        $data['update_time'] = time();

        $data['status']      = 1;

        $res = $this->insert($data);

        return $res;
    }





    /**
     * @author chenniang
     * @DataTime: 2020-04-26 17:08
     * @功能说明:详情
     */
    public function storedInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-26 17:13
     * @功能说明:编辑
     */
    public function storedUpdate($dis,$data){

        $data['update_time'] = time();

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-08 16:30
     * @功能说明:添加用户的优惠券
     */
    public function insertCoupon($id,$user_id,$uniacid){


        $order = [

            'uniacid' => $uniacid,

            'user_id' => $user_id,

            'to_uid'  => 0
        ];


        $dis = [

            'a.stored_id' => $id
        ];


        $data = $this->alias('a')
            ->join('longbing_card_coupon b','a.coupon_id = b.id')
            ->where($dis)
            ->group('a.coupon_id')
            ->field('b.*,a.num as coupon_num')
            ->select()
            ->toArray();

        $record_model = new IndexCouponRecord();

        if(!empty($data)){

            foreach ($data as $coupon){

                for ($i=0;$i<$coupon['coupon_num'];$i++){

                    if(!isset($order['staff_id'])&&isset($order['to_uid'])){

                        $order['staff_id'] = $order['to_uid'];
                    }
                    //领取优惠券
                    $record_model->insertRecord($coupon,$order);

                }

            }

        }

        return true;
    }











}